home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 8151 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.6 KB

  1. Path: rcp6.elan.af.mil!rscernix!danpop
  2. From: danpop@mail.cern.ch (Dan Pop)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Generating pointer to struct from string
  5. Date: 27 Feb 96 22:55:01 GMT
  6. Organization: CERN European Lab for Particle Physics
  7. Message-ID: <danpop.825461701@rscernix>
  8. References: <4grk4g$hep@fmsu03.fm.intel.com>
  9. NNTP-Posting-Host: ues5.cern.ch
  10. X-Newsreader: NN version 6.5.0 #7 (NOV)
  11.  
  12. In <4grk4g$hep@fmsu03.fm.intel.com> vdalvi@mcd.intel.com (Vishram Dalvi) writes:
  13.  
  14. >Say I have 3 structs aaa, bbb and ccc of type foo:
  15. >
  16. >struct foo {
  17. >    int flag;
  18. >    char name[30]
  19. >} aaa, bbb, ccc;
  20. >
  21. >I assign some values to the data members of all 3 structs. Now I prompt the
  22. >user for the name of one of these structs. I read in the user entry into a
  23. >char array. Assume that the user entered "aaa". How can I generate a pointer
  24. >to the struct "aaa" from the user entry?
  25. >I do not want a switch/case table (if user entered "aaa", access members of
  26. >"aaa", if user entered "bbb"...).
  27. >How do I cast a string into a struct address??
  28.  
  29. You don't and you can't use a switch, either.  Your options are:
  30.  
  31. 1. An ugly if/else if/else sequence, testing for all the possible
  32.    variable names.
  33.  
  34. 2. A symbol table.  K&R2 will show you how to implement a symbol table
  35.    using a binary tree.
  36.  
  37. For a trivial case like yours, when everything is known at compile time
  38. and the number of symbols is very small, the first approach is the way
  39. to go.  That is, unless you can redesign your application, using an array
  40. of struct's.
  41.  
  42. Dan
  43. --
  44. Dan Pop
  45. CERN, CN Division
  46. Email: danpop@mail.cern.ch 
  47. Mail:  CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
  48.